package com.example.demo.service.impl;

import com.example.demo.controller.TeamDashboardVO;
import com.example.demo.controller.MemberContributionVO;
import com.example.demo.entity.Team;
import com.example.demo.entity.TeamMember;
import com.example.demo.entity.StudentProgress;
import com.example.demo.mapper.TeamMapper;
import com.example.demo.mapper.TeamMemberMapper;
import com.example.demo.mapper.StudentProgressMapper;
import com.example.demo.service.TeamDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
@Transactional
public class TeamDashboardServiceImpl implements TeamDashboardService {

    @Autowired
    private TeamMapper teamMapper;

    @Autowired
    private TeamMemberMapper teamMemberMapper;

    @Autowired
    private StudentProgressMapper studentProgressMapper;

    @Override
    public Optional<Team> findById(Long id) {
        return teamMapper.findById(id);
    }


    @Override
    public TeamDashboardVO getTeamDashboard(Long teamId) {
        Team team = teamMapper.findById(teamId)
                .orElseThrow(() -> new RuntimeException("团队不存在: " + teamId));

        TeamDashboardVO dashboard = new TeamDashboardVO();
        dashboard.setTeamId(teamId);
        dashboard.setTeamName(team.getTeamName());

        // 计算团队得分和排名
        calculateTeamScoreAndRanking(teamId, dashboard);

        // 计算成员贡献度
        calculateMemberContributions(teamId, dashboard);

        // 计算团队进度
        calculateTeamProgress(teamId, dashboard);

        return dashboard;
    }

    @Override
    public MemberContributionVO getMemberContribution(Long teamId, Long studentId) {
        // 检查学生是否在团队中
        TeamMember member = teamMemberMapper.findByTeamIdAndStudentId(teamId, studentId)
                .orElseThrow(() -> new RuntimeException("该学生不在团队中"));

        MemberContributionVO contribution = new MemberContributionVO();
        contribution.setStudentId(studentId);
        contribution.setStudentName(getStudentName(studentId));
        contribution.setRole(member.getRole().toString());

        // 计算个人贡献度
        Double contributionRate = calculateIndividualContribution(teamId, studentId);
        contribution.setContributionRate(contributionRate);

        // 获取个人完成的任务数
        Integer completedTasks = getCompletedTasksCount(teamId, studentId);
        contribution.setCompletedTasks(completedTasks);

        // 获取个人得分
        Double personalScore = getStudentTotalScore(studentId);
        contribution.setPersonalScore(personalScore);

        return contribution;
    }

    @Override
    public void calculateTeamScoreAndRanking(Long teamId, TeamDashboardVO dashboard) {
        // 获取团队成员
        List<TeamMember> members = teamMemberMapper.findByTeamId(teamId);

        // 计算团队总分
        Double teamScore = 0.0;
        for (TeamMember member : members) {
            List<StudentProgress> progresses = studentProgressMapper.findByStudentId(member.getStudentId());
            for (StudentProgress progress : progresses) {
                if (progress.getScore() != null) {
                    teamScore += progress.getScore();
                }
            }
        }
        dashboard.setTeamScore(teamScore);

        // 计算团队排名（使用Mapper的方法）
        Integer ranking = teamMapper.calculateTeamRanking(teamId);
        dashboard.setTeamRanking(ranking);

        // 设置团队成员数
        dashboard.setTotalMembers(members.size());
    }

    @Override
    public void calculateMemberContributions(Long teamId, TeamDashboardVO dashboard) {
        List<TeamMember> members = teamMemberMapper.findByTeamId(teamId);
        List<TeamDashboardVO.ContributionItem> contributions = new ArrayList<>();

        // 计算每个成员的得分
        Map<Long, Double> memberScores = members.stream()
                .collect(Collectors.toMap(
                        TeamMember::getStudentId,
                        member -> getStudentTotalScore(member.getStudentId())
                ));

        // 计算团队总分
        Double totalTeamScore = memberScores.values().stream()
                .mapToDouble(Double::doubleValue)
                .sum();

        for (TeamMember member : members) {
            TeamDashboardVO.ContributionItem item = new TeamDashboardVO.ContributionItem();
            item.setStudentId(member.getStudentId());
            item.setStudentName(getStudentName(member.getStudentId()));
            item.setRole(member.getRole().toString());

            // 计算贡献度百分比
            Double studentScore = memberScores.get(member.getStudentId());
            Double contributionRate = totalTeamScore > 0 ? (studentScore / totalTeamScore) * 100 : 0.0;
            item.setContributionRate(Math.round(contributionRate * 100.0) / 100.0);

            // 计算完成任务数
            Integer completedTasks = getCompletedTasksCount(teamId, member.getStudentId());
            item.setCompletedTasks(completedTasks);

            // 设置个人得分
            item.setPersonalScore(studentScore);
            contributions.add(item);
        }

        dashboard.setContributions(contributions);
    }

    @Override
    public void calculateTeamProgress(Long teamId, TeamDashboardVO dashboard) {
        List<TeamMember> members = teamMemberMapper.findByTeamId(teamId);

        // 获取课程ID（假设团队成员都在同一个课程）
        Long courseId = teamMapper.findById(teamId).get().getCourseId();

        // 计算总任务数（简化实现）
        Integer totalAssignments = getTotalAssignmentsCount(courseId);

        // 计算团队完成的任务数
        Integer completedAssignments = 0;
        for (TeamMember member : members) {
            completedAssignments += getCompletedAssignmentsCount(member.getStudentId(), courseId);
        }

        TeamDashboardVO.ProgressInfo progressInfo = new TeamDashboardVO.ProgressInfo();
        progressInfo.setTotalAssignments(totalAssignments);
        progressInfo.setCompletedAssignments(completedAssignments);
        progressInfo.setCompletionRate(totalAssignments > 0 ?
                (double) completedAssignments / totalAssignments * 100 : 0.0);

        dashboard.setTeamProgress(progressInfo);
    }

    // ========== 私有辅助方法 ==========

    private Double calculateIndividualContribution(Long teamId, Long studentId) {
        // 获取学生总分
        Double studentScore = getStudentTotalScore(studentId);

        // 获取团队总分
        Double teamScore = getTeamTotalScore(teamId);

        return teamScore > 0 ? (studentScore / teamScore) * 100 : 0.0;
    }

    private Double getStudentTotalScore(Long studentId) {
        List<StudentProgress> progresses = studentProgressMapper.findByStudentId(studentId);
        return progresses.stream()
                .filter(progress -> progress.getScore() != null)
                .mapToDouble(StudentProgress::getScore)
                .sum();
    }

    private Double getTeamTotalScore(Long teamId) {
        List<TeamMember> members = teamMemberMapper.findByTeamId(teamId);
        return members.stream()
                .mapToDouble(member -> getStudentTotalScore(member.getStudentId()))
                .sum();
    }

    private Integer getCompletedTasksCount(Long teamId, Long studentId) {
        List<StudentProgress> progresses = studentProgressMapper.findByStudentId(studentId);
        return (int) progresses.stream()
                .filter(progress -> isCompleted(progress.getCompletionStatus()))
                .count();
    }

    private Integer getCompletedAssignmentsCount(Long studentId, Long courseId) {
        List<StudentProgress> progresses = studentProgressMapper.findByStudentIdAndCourseId(studentId, courseId);
        return (int) progresses.stream()
                .filter(progress -> isCompleted(progress.getCompletionStatus()))
                .count();
    }

    private Integer getTotalAssignmentsCount(Long courseId) {
        // 这里需要根据你的业务逻辑实现
        // 简化返回一个固定值
        return 10;
    }

    private boolean isCompleted(StudentProgress.CompletionStatus status) {
        return status != null && status == StudentProgress.CompletionStatus.COMPLETED;
    }

    private String getStudentName(Long studentId) {
        // 这里需要调用学生服务或查询学生表
        // 简化返回学生ID
        return "学生_" + studentId;
    }
}